<template>
    <div style="padding-left: 20px; padding-right: 20px; padding-top: 20px">
        <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
                <header-toolbar :buttons="headerButton" @delete="handleDelete" @refresh="handleRefresh"
                    @save="handleSave" @submit="handleSubmit" @back="handleReturnList" @approve="handleApprove"
                    @print="handlePrint" @unsubmit="handleUnSubmit" @push="handlePushOrder" @copy="handleCopy"
                    :status.sync="requisition.status"
                    :activeSaveMethod="() => { return requisition.status == 1 || requisition.status == 2 || requisition.status == 3 }"
                    @pushButtonClick="handlePushClick">
                    <template v-slot:pushButton>
                        <el-dropdown-item command="pushPayment" icon="el-icon-download">付款单</el-dropdown-item>
                    </template>
                </header-toolbar>
            </div>
            <div class="text item">
                <el-form :model="requisition" :rules="headerRules" ref="requisitionForm" label-width="100px"
                    label-position="rigth">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="单据编号" prop="number">
                                <el-input v-model="requisition.number" disabled
                                    :placeholder="requisition.id ? '' : '保存后自动生成'"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="类型" prop="type">
                                <el-select v-model="requisition.type" placeholder="请选择类型" :disabled="readonly"
                                    style="width: 100%;" @change="handleChangeProductType">
                                    <el-option :value="1" label="采购付款"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="申请日期" prop="date">
                                <el-date-picker v-model="requisition.date" type="date" placeholder="选择日期"
                                    :disabled="readonly">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="单据状态" prop="status">
                                <status-label :status.sync="requisition.status">
                                </status-label>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="交易对象" prop="tradingPartnerType">
                                <tradingPartner-select v-model="requisition.tradingPartnerType"
                                    @change="() => requisition.supplierId = null" :disabled="readonly">
                                </tradingPartner-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="供应商" prop="supplierId" v-show="requisition.tradingPartnerType == 1">
                                <supplier-select v-model="requisition.supplierId"
                                    :departmentId.sync="requisition.departmentId"
                                    :disabled.sync="!requisition.departmentId" :disabled="readonly">
                                </supplier-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <!-- <el-form-item label="客户" prop="customerId" v-show="requisition.tradingPartnerType == 2">
                                <employee-select v-model="requisition.employeeId"
                                    :departmentId.sync="requisition.departmentId"
                                    :disabled.sync="!requisition.departmentId" :disabled="readonly">
                                </employee-select>
                            </el-form-item> -->
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="员工" prop="employeeId" v-show="requisition.tradingPartnerType == 3">
                                <employee-select v-model="requisition.employeeId"
                                    :departmentId.sync="requisition.departmentId"
                                    :disabled.sync="!requisition.departmentId" :disabled="readonly">
                                </employee-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="币别" prop="currencyId">
                                <currency-select v-model="requisition.currencyId" placeholder="请选择币别"
                                    :disabled="readonly" @change="handleChangeCurrency">
                                </currency-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="汇率" prop="exchangeRate">
                                <number-input v-model="requisition.exchangeRate" :precision="6" :min="0"
                                    controls-position="right" style="width: 100%;" :disabled="readonly"
                                    @change="handleChangeExchangeRate"></number-input>
                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="预付" prop="isAdvanced">
                                <el-checkbox v-model="requisition.isAdvanced" :disabled="readonly"></el-checkbox>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="备注" prop="comment">
                                <el-input v-model="requisition.comment" :disabled="readonly"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-card>
        <el-divider></el-divider>
        <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
                <body-toolbar :table="$refs.xTable" @add="handleAddItem" @delete="handleBodyDelete" @fill="handleFill"
                    :status.sync="requisition.status" :buttons="bodyButton"></body-toolbar>
            </div>
            <div class="text item">
                <vxe-table border align="center" show-footer :data="requisition.items" auto-resize :export-config="{}"
                    resizable ref="xTable" :show-overflow="true" @cell-click="handleCellClick" size="small"
                    :edit-rules="bodyRules" :mouse-config="{ selected: true }" :checkbox-config="{ range: true }"
                    :keyboard-config="{
                        isArrow: true,
                        isDel: false,
                        isEnter: true,
                        isTab: true,
                        isEdit: true,
                    }" :edit-config="{
                        trigger: 'click',
                        mode: 'cell',
                        activeMethod: handleCellEnableEdit,
                    }" :footer-method="handleFooterData" :merge-footer-items="mergeFooterItems">
                    <vxe-table-column type="checkbox" width="40" fixed="left"></vxe-table-column>
                    <vxe-table-column type="seq" width="40" fixed="left"></vxe-table-column>
                    <vxe-table-column field="payableAmountFr" title="应付金额" align="left" header-align="center"
                        width="200" fixed="left" :edit-render="{
                            attrs: {},
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.payableAmountFr | money }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <number-input v-model="row.payableAmountFr" :precision="4"
                                optionClass="vxe-table–ignore-clear"></number-input>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="requisitionAmountFr" title="申请金额" align="left" header-align="center"
                        width="200" :edit-render="{
                            attrs: {},
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                {{ row.requisitionAmountFr | money }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <number-input v-model="row.requisitionAmountFr" :precision="4"
                                optionClass="vxe-table–ignore-clear"></number-input>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="dueDate" title="到期日" align="left" header-align="center" :edit-render="{
                        attrs: {},
                        enabled: !this.readonly,
                    }">
                        <template #default="{ row }">
                            <div>
                                {{ row.dueDate | date }}
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <el-date-picker v-model="row.dueDate" type="date" :picker-options="pickerOptions"
                                popper-class="vxe-table–ignore-clear" format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="expectedPaymentDate" title="期望付款日期" align="left" header-align="center"
                        :edit-render="{
                            attrs: {},
                            enabled: !this.readonly,
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.expectedPaymentDate | date }}</span>
                            </div>
                        </template>
                        <template #edit="{ row }">
                            <el-date-picker v-model="row.expectedPaymentDate" type="date"
                                :picker-options="pickerOptions" popper-class="vxe-table–ignore-clear"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                        </template>
                    </vxe-table-column>
                    <vxe-table-column field="sourceDocumentType" title="源单类型" align="left" header-align="center"
                        :edit-render="{
                            attrs: {},
                            enabled: false,
                        }">
                        <template #default="{ row }">
                            <div>
                                <document-type-label :documentType="row.sourceDocumentType"></document-type-label>
                            </div>
                        </template>

                    </vxe-table-column>
                    <vxe-table-column field="sourceDocumentNumber" title="源单编号" align="left" header-align="center"
                        :edit-render="{
                            attrs: {},
                            enabled: false,
                        }">
                        <template #default="{ row }">
                            <div>
                                <span>{{ row.sourceDocumentNumber | date }}</span>
                            </div>
                        </template>
                    </vxe-table-column>
                </vxe-table>
            </div>
        </el-card>
        <el-drawer direction="rtl" :visible.sync="editAttachmentDrawer" :with-header="false">
            <div v-if="editAttachmentDrawer">
                <attachment-panel :moduleCode="'purchaseRequisition'" :ownerId="requisition.id"></attachment-panel>
            </div>
        </el-drawer>
        <print-dialog ref="printPanel" :moduleCode="'purchaseRequisition'" :ids="[this.id]"></print-dialog>
    </div>
</template>
<script>
import {
    getRequisition,
    addRequisition,
    updateRequisition,
    deleteRequisition,
    updateRequisitionStatus,
    pushPayment,
    updateStatus
} from "@/api/treasury/paymentRequisition";

import headerToolbar from "@/components/Bar/documentHeaderToolbar.vue";
import bodyToolbar from "@/components/Bar/documentBodyToolbar.vue";
import currencySelect from "@/components/Select/currencySelect.vue";
import departmentSelect from "@/components/Select/departmentSelect.vue";
import employeeSelect from "@/components/Select/employeeSelect.vue";
import supplierSelect from "@/components/Select/supplierSelect.vue";
import attachmentPanel from "@/components/Attachment/index.vue";
import printDialog from "@/components/Print/index.vue";
import numberInput from "@/components/Input/numberInput.vue";
import statusLabel from "@/components/Label/documentStatusLabel.vue";
import tradingPartnerSelect from "@/components/Select/tradingPartnerTypeSelect.vue";
import documentTypeLabel from "@/components/Label/documentTypeLabel.vue";
import bankSelect from "@/components/Select/bankSelect.vue";
export default {
    components: {
        headerToolbar,
        bodyToolbar,
        currencySelect,
        departmentSelect,
        employeeSelect,
        supplierSelect,
        attachmentPanel,
        printDialog,
        numberInput,
        statusLabel,
        tradingPartnerSelect,
        documentTypeLabel,
        bankSelect
    },
    data() {
        return {
            requisition: {
                id: null,
                number: null,
                type: 1,
                date: null,
                currencyId: null,
                exchangeRate: null,
                comment: null,
                applicantId: null,
                departmentId: null,
                status: 1,
                items: []
            },
            headerRules: {
                date: [
                    {
                        required: true,
                        message: "请选择日期",
                        trigger: "change",
                    },
                ],
                type: [
                    {
                        required: true,
                        message: "请选择类型",
                        trigger: "change",
                    },
                ],
                currencyId: [
                    {
                        required: true,
                        message: "请选择币别",
                        trigger: "change",
                    },
                ],
                exchangeRate: [
                    {
                        required: true,
                        message: "请填写汇率",
                        trigger: "change",
                    },
                ],
                tradingPartnerType: [
                    {
                        required: true,
                        message: "请选择交易对象",
                        trigger: "change",
                    },
                ]
            },
            bodyRules: {
                requisitionAmountFr: [{ required: true, message: "请填写申请金额" }]
            },
            isModifying: false,
            mergeFooterItems: [{ row: 1, col: 2, rowspan: 1, colspan: 6 }],
            editAttachmentDrawer: false,
            currentCell: { row: null, column: null },
            headerButton: ['save', 'submit', 'unsubmit', 'delete', 'back', 'approve', 'unapprove', 'print', 'push', 'copy'],
            bodyButton: ["add", "remove", "batch-fill"],
            pickerOptions: {
                cellClassName: "vxe-table–ignore-clear"
            },
        };
    },
    methods: {
        getData() {
            if (!this.id) {
                this.setDefaultInfo();
                return;
            }
            getRequisition(this.id).then((res) => {
                this.requisition = res || {};
            });
        },
        handleRefresh() {
            this.getData();
        },
        handleReturnList() {
            if (this.isModifying) {
                this.$confirm("当前数据为保存，是返回列表?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.$router.push({
                            name: "Purchaserequisition",
                        });
                    })
                    .catch(() => { });
            } else {
                this.$router.push({
                    name: "Purchaserequisition",
                });
            }
        },
        handleAddItem() {
            let item = this.getDefaultValueItem();

            this.$refs.xTable.insertAt(item, -1);
            this.requisition.items.push(item);
        },
        handleDelete() {
            let id = this.requisition.id;
            if (!id)
                return;
            deleteRequisition(id).then((res) => {
                this.$notify({
                    title: "成功",
                    message: "删除成功",
                    type: "success",
                    position: "bottom-right",
                });
                this.handleReturnList();
            });
        },
        handleApprove(approved) {
            let status = approved ? 4 : 3;

            this.changeStatus(status)
        },
        async handleSave() {
            await this.validate(() => {
                this.saveData();
            })
        },
        handleSubmit() {
            this.changeStatus(3)
        },
        handleUnSubmit() {
            this.changeStatus(2)
        },
        async validate(callback) {
            const v1 = new Promise((resolve, reject) => {
                this.$refs.requisitionForm.validate(valid => {
                    if (valid) resolve();
                }, true);
            });

            const v2 = new Promise((resolve, reject) => {
                this.$refs.xTable.validate(true, (errMap) => {
                    if (errMap) {
                        reject();
                    } else {
                        resolve();
                    }
                });
            });

            Promise.all([v1, v2]).then(() => {
                callback(true);
            });
        },
        saveData() {
            let items = this.getValidItems();

            this.requisition.items = items;
            if (this.id) {
                updateRequisition(this.requisition).then((res) => {
                    if (res) {
                        this.requisition = res;
                        this.$notify({
                            title: "成功",
                            message: "保存成功",
                            type: "success",
                            position: "bottom-right",
                        });
                    }
                });
            } else {
                addRequisition(this.requisition).then((res) => {
                    if (res) {
                        this.requisition = res;
                        this.$notify({
                            title: "成功",
                            message: "保存成功",
                            type: "success",
                            position: "bottom-right",
                        });
                    }
                });
            }
        },
        changeStatus(status) {
            updateStatus(this.requisition.id, status).then(res => {
                let message = "";
                if (status == 3 && this.requisition.status == 2)
                    message = "提交成功";
                else if (status == 2 && this.requisition.status == 3)
                    message = "撤销提交成功";
                else if (status == 3 && this.requisition.status == 4)
                    message = "反审核成功";

                this.$notify({
                    title: "成功",
                    message: message,
                    type: "success",
                    position: "bottom-right",
                });
                this.getData();
            })
        },
        getValidItems() {
            let items = this.requisition.items.filter(x => x.requisitionAmountFr);

            if (!items)
                return [];

            for (let i = 0; i < items.length; i++) {
                items[i].index = i + 1;
            }
            return items;
        },
        handleCellEnableEdit({ row, rowIndex, column, columnIndex }) {
            return true;
        },
        handleCellClick({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
            this.currentCell = { row: row, column: column }
        },
        getDefaultValueItem() {
            return {
                id: null,
                remark: null,
                productId: null,
                productCode: null,
                productName: null,
                requisitionUnitId: null,
                requisitionUnitName: null,
                requisitionQuantity: null,
                price: null,
                priceIncludeTax: null,
                priceExcludeTax: null,
                taxRateId: null,
                taxRateName: null,
                taxRateValue: null,
                basicUnitId: null,
                basicUnitName: null,
                basicQuantity: null,
                conversionRate: null,
                approvedQuantity: null
            };
        },
        handleFooterData({ columns, data }) {
            let result = [];

            let subTotalRow = columns.map((column, _columnIndex) => {
                if (_columnIndex === 0) {
                    return "";
                }

                if (_columnIndex === 1) {
                    return "";
                }
                if (
                    ![
                        "amountFr",
                        "taxAmountFr",
                        "totalAmountFr"
                    ].includes(column.property)
                ) {
                    return "";
                }

                let total = 0;
                data.forEach((item) => {
                    if (item[column.property]) total = total + +item[column.property];
                });
                return total.toMoney();
            });

            result.push(subTotalRow);
            return result;
        },
        handleChangeProductType() {
            this.$confirm("更改类型会清空分录行，是否继续", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.requisition.items = [];
                })
                .catch(() => { });
        },
        handleChangeCurrency(currency) {
            this.requisition.currencyName = currency.currencyName;
            this.requisition.exchangeRate = currency.exchangeRate;
            let items = this.requisition.items;
            if (!items || items.length == 0)
                return;
            items.forEach(item => {
                calculateAmount(this.requisition.includeTax, this.requisition.exchangeRate, item, this.quantityField);
            })

        },
        handleChangeExchangeRate(item, value) {
            calculateAmount(this.requisition.includeTax, item.exchangeRate, item, this.quantityField);
        },
        handleChangeIncludeTax() {
            let items = this.requisition.items;
            if (!items || items.length == 0)
                return;
            items.forEach(item => {
                calculateAmount(this.requisition.includeTax, this.requisition.exchangeRate, item, this.quantityField);
            })
        },
        handleChangeProduct(item, product) {
            if (!product)
                return;
            item.productName = product.name;
            item.productCode = product.code;
            item.productModel = product.model;
            item.basicUnitId = product.basicUnitId;
            item.basicUnitName = product.basicUnitName;
            item.taxRateId = product.defaultTaxRateId;
            item.taxRateName = product.defaultTaxRateName;
            item.taxRateValue = product.defaultTaxRateValue;

            this.setPurchaseDefaultInfo(item, product.id);
            setUnitConversionRate(item, this.auxiliaryUnitField);
        },
        handleChangeUnit(item, unit) {
            item.requisitionUnitName = unit.otherUnitName;
            item.conversionRate = unit.conversionRate;

            calculateBasicQuantity(item, this.quantityField)

        },
        handleSupplierChange(item, supplier) {
            item.suggestedSupplierName = supplier.name;
        },

        setDefaultInfo() {
            this.requisition.date = new Date();
            if (this.requisition.items && this.requisition.items.length > 0) return;
            //默认插四行数据
            for (let i = 0; i < 1; i++) {
                let item = this.getDefaultValueItem();
                this.requisition.items.push(item);
            }
        },
        handleAttachment() {
            this.editAttachmentDrawer = true;
        },
        handlePrint() {
            this.$refs.printPanel.showDialog();
        },
        handleBodyDelete({ ids, rows }) {
            if (rows.length == 0)
                return;

            let xids = rows.map((data) => {
                return data._XID;
            });

            this.requisition.items = this.requisition.items.filter((item) => {
                return xids.indexOf(item._XID) < 0
            })
        },
        handleFill() {
            if (!this.currentCell || !this.currentCell.row || this.requisition.items.length == 0)
                return;
            let row = this.currentCell.row;
            let column = this.currentCell.column;

            //有些字段不允许批量填充
            if (column.property == "productCode") {
                return;
            }

            this.requisition.items.forEach(item => {
                let columnNames = [column.property];

                if (column.property == "suggestedSupplierId") {
                    columnNames.push("suggestedSupplierName")
                } else if (column.property == "taxRateId") {
                    columnNames.push("taxRateName")
                } else if (column.property == "requisitionUnitId") {
                    columnNames.push("requisitionUnitName");
                }
                columnNames.forEach(columnName => {
                    item[columnName] = row[columnName];
                    //未提交状态的批准数量等于申请数量
                    if (columnName == "requisitionQuantity" && this.requisition.status == 2) {
                        item["approvedQuantity"] = row[columnName]
                    }
                })

            })
        },
        handlePushClick(command) {
            if (command == "pushPayment") {
                this.handlePushPayment();
            }
        },
        handlePushPayment() {
            var id = this.requisition.id;

            if (!id) return;

            pushPayment(id).then(res => {
                if (!res)
                    return;
                this.$notify({
                    title: "成功",
                    message: "下推成功",
                    type: "success",
                    position: "bottom-right",
                });
            })
        },
        handleCopy() {

        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getData();
        });
    },
    computed: {
        id() {
            return this.$route.query.id;
        },
        readonly() {
            return this.requisition.status != 1 && this.requisition.status != 2;
        },
        productTypes() {
            if (!this.requisition.productType)
                return null;

            return [this.requisition.productType];
        }
    },
    watch: {},
    props: {
        model: {
            type: Object,
            default: () => null
        },
    }
};
</script>
<style scoped></style>